from django.http import HttpResponse


class CorsMiddleware:
    """中间件：为响应添加跨域头"""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 处理 OPTIONS 请求（预检）
        if request.method == 'OPTIONS':
            response = self.handle_options_request(request)
            return response

        response = self.get_response(request)
        response = self.add_cors_headers(response)
        return response

    def handle_options_request(self, request):
        """处理 OPTIONS 请求，返回 200 响应并设置 CORS 头"""
        response = HttpResponse()
        response = self.add_cors_headers(response)
        return response

    def add_cors_headers(self, response):
        """为响应添加 CORS 相关头信息"""
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS, PATCH'
        response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
        response['Access-Control-Allow-Credentials'] = 'true'
        return response

    def process_template_response(self, request, response):
        return self.add_cors_headers(response)

    def process_response(self, request, response):
        return self.add_cors_headers(response)